package br.com.gsc.vaadin;

import java.lang.reflect.Constructor;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;

import br.com.gsc.model.tableMapping.TopicTypes;
import br.com.gsc.repository.objRepos.ProductRepository;
import br.com.gsc.repository.objRepos.TopicRepository;
import br.com.gsc.setup.AuthenticationHolder;

import com.vaadin.terminal.Sizeable;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Component;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Panel;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

@Configurable(preConstruction=true)
public class OperatorWindow extends Window {

	
   // The default application's inner window width using CSS style
   public static final String DEFAULT_INNER_WINDOW_WIDTH = "600px";
   // The default application's inner window height using CSS style
   public static final String DEFAULT_INNER_WINDOW_HEIGHT = "650px";
   // The default distance of Window left border in pixels from left border of the containing (main window).
   public static final int DEFAULT_INNER_WINDOW_LEFT_BORDER = 30;
   // The default distance of Window top border in pixels from left border of the containing (main window).
   public static final int DEFAULT_INNER_WINDOW_TOP_BORDER = 30;
   public static final int DEFAULT_WINDOW_BUTTON_WIDTH = 200;	

	private static final long serialVersionUID = -1481084776783567319L;
	private VerticalLayout vertLayout;
	private MenuBar menu;
	private Panel centralPanel;
	private Button btnPerguntas;
	private Button btnSugestoes;
	private Button btnReclamacoes;
	private Button btnOpnioes;
	
	private static final Logger logger = Logger.getLogger(VaadinAdminServlet.class.getName());

	@Autowired
	AuthenticationHolder auth;	   

	@Autowired
	private transient TopicRepository tRepo;
	
	@Autowired
	private transient ProductRepository proRepo;

	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public OperatorWindow() {

		this.init();

	}

//	public void populatePerguntasPanel(){
//		Product prod =  proRepo.findTProductByID((long)1);		
//		for(Topic top:prod.getListOfTopics()){
//			if(top.getTopicType().equals(TopicTypes.QUESTION)){
//				Panel p = new Panel();
//				Label l = new Label(top.getTopicTitle());
//				p.addComponent(l);
//				PeContent.addComponent(p);
//			}			
//		}
//	}	  
	   
	   
	public void init() {
		createWindow();
		
	}
	
	public void createWindow(){				
		createComponents();
		this.setSizeFull();
		this.getContent().setSizeFull();
	}
	
	   /**
	    * Metodo que cria os componentes visuais. Chama o metodo para criar o painel central.
	    */
	   public void createComponents()
	   {
	      vertLayout = new VerticalLayout();
	      vertLayout.setMargin(false, true, false, true);
	      vertLayout.setSpacing(true);
	      vertLayout.addComponent(menuCreator());
	      vertLayout.addComponent(centralPanelCreator());
	      vertLayout.setComponentAlignment(centralPanel, Alignment.MIDDLE_CENTER);
	      vertLayout.setExpandRatio(centralPanel, 1.0f);
	      vertLayout.setSizeFull();
	      this.setContent(vertLayout);
	   }
	   
	   private Component centralPanelCreator()
	   {
	      centralPanel = new Panel("Controles");
//	      centralPanel.setHeight(600, Sizeable.UNITS_PIXELS);
	      centralPanel.setHeight(100, Sizeable.UNITS_PERCENTAGE);
	      centralPanel.setWidth(100, Sizeable.UNITS_PERCENTAGE);
	      centralPanel.getContent().setSizeFull();
	      HorizontalLayout firstHorzRow = new HorizontalLayout();
	      firstHorzRow.setSpacing(true);
	      firstHorzRow.setMargin(true);
	      firstHorzRow.setHeight("300px");
	      firstHorzRow.setWidth("100%");

	      HorizontalLayout secondHorzRow = new HorizontalLayout();
	      secondHorzRow.setSpacing(true);
	      secondHorzRow.setMargin(true);
	      secondHorzRow.setHeight("300px");
	      secondHorzRow.setWidth("100%");	    	     
	      
			btnPerguntas = new DefaultMainWindowButtonComponent(
					"Perguntas", "img/perguntas.png", GenericAnswerWindow.class, TopicTypes.QUESTION);
		      firstHorzRow.addComponent(btnPerguntas);
		      firstHorzRow.setComponentAlignment(btnPerguntas, Alignment.MIDDLE_CENTER);	      
	      
			btnSugestoes = new DefaultMainWindowButtonComponent(
					"Sugestoes", "img/idea.png", GenericAnswerWindow.class, TopicTypes.IDEA);
		      firstHorzRow.addComponent(btnSugestoes);
		      firstHorzRow.setComponentAlignment(btnSugestoes, Alignment.MIDDLE_CENTER);

			btnReclamacoes = new DefaultMainWindowButtonComponent(
					"Reclamacoes", "img/reclamacao.png", GenericAnswerWindow.class,TopicTypes.PROBLEM);
		      secondHorzRow.addComponent(btnReclamacoes);
		      secondHorzRow.setComponentAlignment(btnReclamacoes, Alignment.MIDDLE_CENTER);	      
	      
			btnOpnioes = new DefaultMainWindowButtonComponent(
					"Opnioes", "img/sugestao.png", GenericAnswerWindow.class,TopicTypes.PRAISE);
			secondHorzRow.addComponent(btnOpnioes);
			secondHorzRow.setComponentAlignment(btnOpnioes, Alignment.MIDDLE_CENTER);
	    
	      
	      centralPanel.addComponent(firstHorzRow);
	      centralPanel.addComponent(secondHorzRow);
	      return centralPanel;	    
	   }
	   
	   private Component menuCreator()
	   {
	      menu = new MenuBar();
	      menu.setWidth(100, Sizeable.UNITS_PERCENTAGE);
	      MenuItem arquivos = menu.addItem("Arquivos", null);
	      arquivos.addItem("Abrir", null);
	      arquivos.addItem("Salvar", null);
	      arquivos.setEnabled(false);
	      MenuItem reposts = menu.addItem("Reports", null);
	      reposts.addItem("Teste 1", menuCommand);
	      reposts.setEnabled(false);
	      MenuItem graficos = menu.addItem("Graficos", null);
	      graficos.setEnabled(false);
	      return menu;
	   }
	   
	   private Command menuCommand = new Command()
	   {
		private static final long serialVersionUID = -5401829687662729364L;

	      public void menuSelected(MenuItem selectedItem)
	      {
//	         getMainWindow().addWindow(hh);
//	         hh.setPositionX(25);
//	         hh.setPositionY(25);
//	         hh.setVisible(true);
	      }
	   };
	   
	   
	   
	   /**
	    * Inner class that concentrates the new Window initializations. This will help on standardization of the application.
	    * Depending on the component that is being created, it may throw many kind of exceptions, therefore this class throws Exception itself. It is up tp the called knowing which kind of Exception it should be captured. 
	    */
	   class DefaultMainWindowButtonComponent extends Button
	   {		  
	      private static final long serialVersionUID = 1L;
	      private static final String STYLENAME = "icon-on-top";
	      public DefaultMainWindowButtonComponent(final String buttonTitle, String buttonIcon, final Class<? extends GenericAnswerWindow> clazz, final Object... parameters)
	      {
	         super(buttonTitle);
	         addStyleName(STYLENAME);
	         addStyleName("stl_button");
	         setWidth(DEFAULT_WINDOW_BUTTON_WIDTH, Sizeable.UNITS_PIXELS);
	         setIcon(new ThemeResource(buttonIcon));
	         addListener(new Button.ClickListener()
	         {
	            private static final long serialVersionUID = 1L;

	            public void buttonClick(ClickEvent event)
	            {
	               logger.info("Button " + event.getButton().getCaption() + " clicked.");
	               DefaultWindowComponent windowComponentToShow;
	               GenericAnswerWindow comp;
	               try
	               {
	            	   if(parameters.length > 0)
	            	   {
	            		   Class<?>[] classArr = new Class[parameters.length];
	            		   int counter = 0;
	            		   do
	            		   {
	            			   classArr[counter] = parameters[counter].getClass();
	            			   counter++;
	            		   }while(counter < parameters.length);
	            		   Constructor<? extends GenericAnswerWindow> cons = clazz.getConstructor(classArr);
	            		   comp = cons.newInstance(parameters);
	                  }else{
	            		   comp = clazz.newInstance();
	                  }
	                  
	                  getApplication().getMainWindow().removeWindow(comp);
	                  getApplication().getMainWindow().addWindow(comp);
	               } catch (Exception e)
	               {
	                  logger.severe("It was not possible to open window");
	                  e.printStackTrace();
	                  
	                  getWindow().showNotification("Erro",
	                		  "Não foi possível abrir a janela. Para mais informaçõees, verifique o log.",
	                          Notification.TYPE_ERROR_MESSAGE);
	               }
	            }
	         });
	      }
	   }
	   
	   /**
	    * Inner class that concentrates the new Window initializations. This will help on standardization of the application.
	    */
	   class DefaultWindowComponent extends Window
	   {
	      private static final long serialVersionUID = 1L;
	      public DefaultWindowComponent(String title, ComponentContainer innerComponent)
	      {
	         super(title, innerComponent);
	         setWidth(DEFAULT_INNER_WINDOW_WIDTH);
	         setHeight(DEFAULT_INNER_WINDOW_HEIGHT);
	         setPositionX(DEFAULT_INNER_WINDOW_LEFT_BORDER);
	         setPositionY(DEFAULT_INNER_WINDOW_TOP_BORDER);
	         logger.fine("Window "+title+ " created.");
	      }      
	   }

}
